import React, { Fragment } from "react";
import { message } from "antd";
import { useRequest } from "ahooks";
import { Space } from "antd";
import { AndroidOutlined, EditOutlined } from "@ant-design/icons";

import SessionList from "./components/session_list";
import MessageTip from "./components/message_tip";
import MessageHistory from "./components/message_history";
import MessageForm from "./components/message_form";
import request, { CustomResponse } from "../../api/http_class";
import {
  ChatCompletionRequestI,
  ChatMessageI,
  SessionMessageI,
} from "../../types/system";
// import { getChatResponse } from "../../api/system";
import styles from "./index.module.less";
import "./index.less";

const Chat: React.FC = () => {
  // 存当前对话，每一项为对话一方的信息描述
  const [chatMessages, setChatMessages] = React.useState<ChatMessageI[]>([]);
  // 存左侧栏会话记录，每一项为一组message
  const [sessionList, setSessionList] = React.useState<SessionMessageI[]>([
    { id: "123", title: "abc", messages: [], archived: false },
    { id: "124", title: "bcd", messages: [], archived: false },
  ]);

  const handleSendMessage = async (values: any) => {
    console.log(values);
    // 先用用户发送的问题加到历史记录中展示，回复完成后再替换成数据库中获取的记录
    const tmpMessage: ChatMessageI = {
      id: Math.random().toString(),
      role: "user",
      content: values.content,
    };
    let tmpMessageList = [...chatMessages, tmpMessage];

    const data: ChatCompletionRequestI = {
      model: values.model,
      messages: [
        {
          role: "user",
          content: values.content,
        },
      ],
    };

    request({
      url: `http://121.36.25.135:8888/api/v1/chat_basic/completions/`,
      // url: `http://127.0.0.1:8001/api/v1/chat_basic/completions/`,
      method: "POST",
      data: data,
    }).then(
      // (res: CustomResponse<ChatCompletionResponseI>) => {
      (res: CustomResponse<any>) => {
        console.log(res);
        console.log(res.data.choices[0].message.content);
        console.log(res.data.choices[0].message.role);
        tmpMessageList.push({
          // id: res.data.choices[0].id,
          id: Math.random().toString(),
          content: res.data.choices[0].message.content,
          role: res.data.choices[0].message.role,
        });
        setChatMessages(tmpMessageList);
      },
      (err: any) => {
        console.log(err);
        message.error("响应失败");
      }
    );
  };

  const handleCreateSession = () => {
    console.log(chatMessages);
    if (chatMessages.length > 0) {
      const newSession: SessionMessageI = {
        id: Math.random().toString(),
        title: chatMessages[0].content,
        archived: false,
        messages: chatMessages,
      };
      const tmpSessionList = [newSession, ...sessionList];
      setSessionList(tmpSessionList);
      setChatMessages([]);
    }
  };

  const handleSwitchSession = (params: SessionMessageI) => {
    console.log(params);
  };

  const { run } = useRequest((values: any) => handleSendMessage(values), {
    manual: true,
    onError(e, params) {
      message.error("获取数据失败");
    },
  });

  return (
    <Fragment>
      <div className={styles.chat}>
        <div className={styles.left}>
          <div onClick={handleCreateSession} className={styles.createBtn}>
            <div>
              <Space>
                <AndroidOutlined />
                <span>创建新会话</span>
              </Space>
            </div>
            <EditOutlined />
          </div>
          <SessionList
            data={sessionList}
            handleSwitchSession={handleSwitchSession}
          ></SessionList>
        </div>
        <div className={styles.right}>
          <div className={styles.message}>
            {chatMessages.length === 0 ? (
              <MessageTip />
            ) : (
              <MessageHistory data={chatMessages} />
            )}
            <MessageForm handleFormSubmit={run} />
          </div>
        </div>
      </div>
    </Fragment>
  );
};

export default Chat;
